/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;
import util.StringUtils;

/**
 *
 * @author Kien.Tran
 */
public class DBManager {

    // database name
    public static final String DB_CONFIG = "vsv_ms_config";
    public static final String DB_HELP = "vsv_ms_help";

    // variable 
    public static final String PARA_APPLICATION = "conf_app";
    public static final String PARA_REINSTALL_TIME = "conf_reinstall";
    
    private static RecordStore rs = null;

    /*
     * count records
     * 
     * */
    public static int count(String db) {
        int result = 0;
        try {
            rs = RecordStore.openRecordStore(db, true);
            result = rs.getNumRecords();
            rs.closeRecordStore();
        } catch (Exception e) {
            rs = null;
            result = -1;
        }
        return result;
    }

    public static boolean truncate(String db) {
        boolean result = true;
        try {
            RecordStore.deleteRecordStore(db);
        } catch (Exception ex) {
            rs = null;
            result = false;
        }
        return result;
    }

    /*
     * insert a record into database
     *
     * */
    public static boolean insert(String db, String data, String key) {
        boolean result = false;
        try {
            rs = RecordStore.openRecordStore(db, true);

            // check whether key is null(empty) or not
            boolean flag = false;
            if ((key != null) && (key.trim().length() > 0)) {
                key = key.trim();
                flag = true;
            }

            // insert data into database
            if ((data != null) && (data.trim().length() > 0)) {
                String s = "";
                if (flag) {
                    s = key + "=" + data.trim();
                } else {
                    s = data.trim();
                }
                byte bytes[] = s.getBytes("UTF-8");
                rs.addRecord(bytes, 0, bytes.length);
            }
            rs.closeRecordStore();
            result = true;
        } catch (Exception ex) {
            rs = null;
            result = false;
        }
        return result;
    }

    /*
     * insert list of records into database
     *
     * */
    public static boolean insert(String db, Vector vector, String key) {
        boolean result = false;
        try {
            rs = RecordStore.openRecordStore(db, true);

            // check whether key is null(empty) or not
            boolean flag = false;
            if ((key != null) && (key.trim().length() > 0)) {
                key = key.trim();
                flag = true;
            }

            String data = null;
            byte bytes[] = null;

            // insert data into database
            for (int i = 0; i < vector.size(); i++) {
                data = (String) vector.elementAt(i);

                if (data != null) {
                    data = data.trim();

                    if (data.length() > 0) {
                        String s = "";
                        if (flag) {
                            s = key + "=" + data;
                        } else {
                            s = data;
                        }
                        bytes = s.getBytes("UTF-8");
                        rs.addRecord(bytes, 0, bytes.length);
                    }
                }
            }
            rs.closeRecordStore();
            result = true;
        } catch (Exception ex) {
            rs = null;
            result = false;
        }
        return result;
    }

    /*
     * update data if it is exist or insert a record
     *
     * */
    public static boolean update(String db, String key, String value) {
        boolean result = false;
        try {
            rs = RecordStore.openRecordStore(db, true);

            boolean isExists = false;
            int index = -1;
            byte bytes[] = null;
            String record = null;

            // find setting to update
            if (rs.getNumRecords() > 0) {
                SearchFilter search = new SearchFilter(key);
                RecordEnumeration re = rs.enumerateRecords(search, null, false);

                while (re.hasNextElement()) {
                    index = re.nextRecordId();
                    record = key + "=" + value;
                    bytes = record.getBytes();
                    rs.setRecord(index, bytes, 0, bytes.length);
                    isExists = true;
                    result = true;
                    break;
                }
            }

            // insert settting if not exists
            if (!isExists) {
                record = key + "=" + value;
                bytes = record.getBytes();
                rs.addRecord(bytes, 0, bytes.length);
                result = true;
            }

            rs.closeRecordStore();
            
        } catch (Exception ex) {
            rs = null;
            result = false;
        }
        return result;
    }

    /*
     * select all records
     *
     * */
    public static Vector selectAll(String db) {
        Vector result = new Vector();
        try {
            rs = RecordStore.openRecordStore(db, true);

            byte bytes[] = null;
            String record = null;

            if (rs.getNumRecords() > 0) {
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                while (re.hasNextElement()) {
                    bytes = re.nextRecord();
                    record = new String(bytes).trim();
                    if (record.length() > 0) {
                        String s = StringUtils.getValue(record, "=");
                        if ((s != null) && (s.length() > 0)){
                            result.insertElementAt(s, 0);
                        }
                    }
                }
            }
            rs.closeRecordStore();
        } catch (Exception ex) {
            rs = null;
            result = null;
        }
        return result;
    }

    /*
     * select all records with key
     *
     * */
    public static Vector select(String db, String key) {
        Vector result = new Vector();
        try {
            rs = RecordStore.openRecordStore(db, true);

            byte bytes[] = null;
            String record = null;

            if (rs.getNumRecords() > 0) {
                SearchFilter filter = new SearchFilter(key);
                RecordEnumeration re = rs.enumerateRecords(filter, null, false);
                while (re.hasNextElement()) {
                    bytes = re.nextRecord();
                    record = new String(bytes).trim();

                    if (record.length() > 0) {
                        String s = StringUtils.getValue(record, "=");
                        if ((s != null) && (s.length() > 0)){
                            result.insertElementAt(s, 0);
                        }
                    }
                }
            }
            rs.closeRecordStore();
        } catch (Exception ex) {
            rs = null;
            result = null;
        }
        return result;
    }

    /*
     * select all records of these keys
     *
     * */
    public static Hashtable select(String db, String[] keys) {
        Hashtable result = new Hashtable();
        try {
            // open record store
            rs = RecordStore.openRecordStore(db, true);

            byte bytes[] = null;
            String record = null;

            // get records
            if (rs.getNumRecords() > 0) {
                RecordEnumeration re = rs.enumerateRecords(null, null, false);

                while (re.hasNextElement()) {
                    bytes = re.nextRecord();
                    record = new String(bytes);
                    
                    if (record.length() > 0){
                        for (int i = 0; i < keys.length; i++){
                            if (record.startsWith(keys[i])){
                                String s = StringUtils.getValue(record, "=");
                                if ((s != null) && (s.length() > 0)){
                                    result.put(keys[i], record);
                                }
                            }
                        }
                    }
                }
            }
            rs.closeRecordStore();
        } catch (Exception ex) {
            rs = null;
            result = null;
        }
        return result;
    }


     /*
     * select a record with key
     *
     * */
    public static String selectOne(String db, String key) {
        try {
            rs = RecordStore.openRecordStore(db, true);

            byte bytes[] = null;
            String record = null;

            if (rs.getNumRecords() > 0) {
                SearchFilter filter = new SearchFilter(key);
                RecordEnumeration re = rs.enumerateRecords(filter, null, false);
                while (re.hasNextElement()) {
                    bytes = re.nextRecord();
                    record = new String(bytes).trim();

                    if (record.length() > 0) {
                        String s = StringUtils.getValue(record, "=");
                        if ((s != null) && (s.length() > 0)){
                            return s;
                        }
                    }
                }
            }
            rs.closeRecordStore();
        } catch (Exception ex) {
            rs = null;
            return null;
        }
        return null;
    }


    /*
     * delete a record by key
     *
     * */
    public static boolean delete(String db, String key) {
        boolean result = false;
        try {
            // open record store
            rs = RecordStore.openRecordStore(db, true);

            // find setting to delete
            if (rs.getNumRecords() > 0) {
                SearchFilter filter = new SearchFilter(key);
                RecordEnumeration re = rs.enumerateRecords(filter, null, false);

                while (re.hasNextElement()) {
                    rs.deleteRecord(re.nextRecordId());
                }
            }
            result = true;            
            rs.closeRecordStore();
        } catch (Exception ex) {
            result = false;
        }
        return result;
    }

    public static boolean saveImage(String db, Image img, int width, int height, String imgName) {

        if (db == null || img == null || width < 0 || height < 0 || imgName == null) {
            throw new IllegalArgumentException("Check arguments");
        }

        int[] imgRgbData = new int[width * height];

        try {
            img.getRGB(imgRgbData, 0, width, 0, 0, width, height);
        } catch (Exception e) {
            // Problem getting image RGB data
            return false;
        }

        try {
            // open record store
            rs = RecordStore.openRecordStore(db, true);

            // Write image data to output stream (in order to get
            // the record bytes in needed form)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeUTF(imgName);

            for (int i = 0; i < imgRgbData.length; i++) {
                dos.writeInt(imgRgbData[i]);
            }

            dos.flush();

            // Open record store, create if it doesn't exist
            rs.addRecord(baos.toByteArray(), 0, baos.toByteArray().length);  // Add record

            dos.close();
            rs.closeRecordStore();

        } catch (RecordStoreNotFoundException rsnfe) {
            // Record storage not found
            return false;
        } catch (RecordStoreException rse) {
            // Other record storage problem
            return false;
        } catch (IOException ioe) {
            // Problem writing data
            return false;
        }

        return true; // We've successfuly done
    }

    public static Image loadImage(String db, int width, int height) {

        if (db == null || width < 0 || height < 0) {
            return null;
        }
        byte[] b = null;
        String imagename = null;
        Image image = null;

        try {
            // open record store
            rs = RecordStore.openRecordStore(db, true);

            int i = rs.getNumRecords();
            for (int j = 1; j < i + 1; j++) {

                if (rs.getRecord(j) != null) {

                    b = rs.getRecord(j);
                    ByteArrayInputStream bin = new ByteArrayInputStream(b);
                    DataInputStream din = new DataInputStream(bin);
                    
                    imagename = din.readUTF();

                    int remaining = (b.length - imagename.getBytes().length - 2) / 4;
                    int[] rawdata = new int[remaining];

                    for (int k = 0; k < rawdata.length; k++) {
                        rawdata[k] = din.readInt();
                    }

                    image = Image.createRGBImage(rawdata, width, height, false);

                    bin.reset();
                    din.close();
                    din = null;
                }
            }

            rs.closeRecordStore();

        } catch (IOException ioe) {
            image = null;

        } catch (RecordStoreException rse) {
            image = null;
        }

        return image;
    }
}
